package com.moore.Servlet;

import com.alibaba.fastjson2.JSON;
import com.moore.net.HttpRequest;
import com.moore.net.HttpResponse;
import com.moore.net.HttpServlet;
import com.moore.utils.OrderUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class OrdersServlet extends HttpServlet {

    @Override
    public byte[] doGet(HttpRequest request, HttpResponse response) {
        String responseData = "";
        String type = request.getParams().get("type");
        String userId = request.getParams().get("userId");
        switch (type) {
            case "get":
                String value;
                try {
                    value = URLDecoder.decode(request.getParams().get("value"),"utf-8");
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
                responseData = JSON.toJSONString(OrderUtils.getOrders(value,userId));
                break;
            case "delete": {
                String id = request.getParams().get("id");
                responseData = OrderUtils.deleteOrders(userId, id);
                break;
            }
            case "add": {
                String goodsId = request.getParams().get("goodsId");
                String unitPrice = request.getParams().get("unitPrice");
                String number = request.getParams().get("number");
                String price = request.getParams().get("price");
                String state = request.getParams().get("state");
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                String time = now.format(formatter);
                responseData = OrderUtils.addOrders(userId, goodsId, unitPrice, number, price, time, state);
                break;
            }
            case "update": {
                String id = request.getParams().get("id");
                String state = request.getParams().get("state");
                responseData = OrderUtils.updateOrders(userId, id, state);
                break;
            }
            case "count": {
                responseData = OrderUtils.getOrdersCount(userId);
                break;
            }
        }
        return responseData.getBytes(StandardCharsets.UTF_8);
    }
}
